<!-- 登录弹窗 -->
<template>
    <div>
        <!-- 弹窗 -->
        <Dialog
            :show="dialogConfig.show"
            :title="dialogConfig.title"
            :draggable="dialogConfig.draggable"
            :top="dialogConfig.top"
            :width="dialogConfig.width"
            :height="dialogConfig.height"
            :loginType="dialogConfig.loginType"
            :callback="dialogConfig.callback"
            @close="close">
            <!-- 邮箱登录 -->
            <div v-if="dialogConfig.loginType == 1">
                <el-form
                    :model="formData"
                    :show-message="false"
                    ref="formDataRef"
                    label-width="auto"
                    class="form-body-email">
                    <div class="email">
                        <!-- 邮箱 -->
                        <el-form-item>
                            <el-input
                                v-model="formData.email"
                                placeholder="请输入邮箱"
                                size="large"
                                @focus="clearErrorMessage(0)"></el-input>
                        </el-form-item>
                    </div>

                    <div class="checkCode">
                        <!-- 验证码 -->
                        <el-form-item>
                            <el-input
                                v-model="formData.code"
                                placeholder="请输入邮箱验证码"
                                size="large"
                                @focus="clearErrorMessage(1)"></el-input>
                        </el-form-item>
                        <button :class="[isCountingDown ? 'counting-down' : '']" @click="getCheckCode">
                            {{ buttonText }}
                        </button>
                    </div>

                    <!-- 错误消息提示 -->
                    <div v-if="showErrorMessage" class="error-message">{{ errorMessage }}</div>

                    <div class="submit">
                        <button @click="submitForm" :disabled="isCountingDown">登录</button>
                    </div>
                </el-form>
            </div>
            <!-- 扫码登录 -->
            <div v-else-if="dialogConfig.loginType == 0">
                <div class="scan-login">
                    <div class="scan">
                        <div class="left">
                            <img src="../assets/Login/phone.png" />
                        </div>
                        <div class="right">
                            <div class="a">扫码登录</div>
                            <div class="b">
                                <img src="../assets/Login/二维码.jpg" />
                            </div>
                            <div class="c">
                                使用
                                <span>网易云音乐APP</span>
                                扫码登录
                            </div>
                        </div>
                    </div>
                    <div class="others">
                        <span @click="showPanel">选择其他登录模式</span>
                    </div>
                </div>
            </div>
            <div v-else class="page-container">
                <el-result icon="info" title="请稍候，正在跳转..." sub-title="系统正在处理您的请求，请耐心等待">
                    <template #extra>
                        <el-icon class="is-loading" :size="30">
                            <Loading />
                        </el-icon>
                    </template>
                </el-result>
            </div>
        </Dialog>
    </div>
</template>

<script setup lang="ts">
import { Loading } from '@element-plus/icons-vue';
import { nextTick, reactive, ref } from 'vue';
import Dialog from '../components/Dialog.vue';
import useStore from '../store/user.ts';
import { $getCode, $Login, $sendSms, $register, $logout } from '../api/user.ts';
import { ElMessage, ElLoading, ElNotification, ElMessageBox } from 'element-plus';

const regEmail = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
const regCheckCode = /^[a-zA-Z0-9]{5}$/;

// 用户状态
const userStore = useStore();

// 获取验证码
const isCountingDown = ref(false);
const countdown = ref(30); // 倒计时60秒
const buttonText = ref('获取验证码');

// 弹窗配置
const dialogConfig = reactive({
    // 是否显示弹窗
    show: false,
    // 弹窗标题
    title: '登录',
    // 是否可以拖拽移动 (默认true)
    draggable: false,
    // 顶部距离
    top: '11%',
    // 弹窗宽度
    width: '530px',
    // 弹窗高度
    height: '326px',
    // 登录类型  0：扫码登录  1：邮箱登录
    loginType: 1,
    // 回调
    callback: () => {
        dialogConfig.title = '登录';
        dialogConfig.loginType = 0;
    }
});

// 表单
const formData = ref({ email: '', code: '' });
const formDataRef = ref();

// 是否显示错误信息 提示
const showMessage = ref(false);
// 错误信息提示
const errorMessage = ref();

let timer = null;

// x 号关闭弹窗
const close = () => {
    dialogConfig.show = false;
};

// 显示登录弹窗
const showPanel = () => {
    showErrorMessage.value = false;
    dialogConfig.title = '邮箱登录';
    dialogConfig.loginType = 1;
    dialogConfig.show = true;
    nextTick(() => {
        formDataRef.value.resetFields();
        formData.value = { email: '', checkCode: '' };
    });
};

// 获取邮箱验证码
const getCheckCode = () => {
    if (timer) {
        return;
    }
    if (formData.value.email == '') {
        errorMessage.value = '请输入邮箱';
        showMessage.value = true;
        return;
    } else if (!regEmail.test(formData.value.email)) {
        errorMessage.value = '邮箱格式错误，请更换后重试';
        showMessage.value = true;
        return;
    }

    // 开始倒计时
    startCountdown();

    // 获取邮箱验证码
    $sendSms(formData.value.email)
        .then((res) => {
            if (res.success) {
                ElMessage.success('邮箱验证码发送成功');
                // console.log(res.result);
            } else {
                ElMessage.error(res.message);
            }
        })
        .catch((error) => {
            // console.error('获取验证码失败:', error);
            ElMessage.error(error.message);
        })
        .finally(() => {
            // 请求结束后关闭加载动画
            // loadingSms.close();
        });
};

// 邮箱登录 提交表单
const submitForm = () => {
    // 校验表单
    showErrorMessage();

    const loginParams = {
        username: formData.value.email,
        captcha: formData.value.code
    }

    // 登录
    $Login(loginParams)
        .then((res) => {
            // console.log(res);
            if (res.success) {
                // 获取当前小时数
                const currentHour = new Date().getHours();

                // 根据小时数判断问候语
                let greeting = '';
                if (currentHour >= 5 && currentHour < 11) {
                    greeting = '早上好';
                } else if (currentHour >= 11 && currentHour < 18) {
                    greeting = '中午好';
                } else {
                    greeting = '晚上好';
                }

                // 显示通知
                ElNotification.success({
                    title: `${greeting}！${res.result.userInfo.nikename}`,
                    message: res.message,
                    showClose: false
                });
                userStore.setAuthData(res.result.token, res.result.userInfo);
                // 获取当前登录状态
                // isLoginIn.value = userStore.isLoggedIn;
                if (userStore.isLoggedIn) {
                    // 登录成功，关闭登录界面
                    dialogConfig.show = false;
                }
            } else {
                ElMessage.error(res.message);
                // getCode();
            }
        })
        .catch((error) => {
            console.error('获取验证码失败:', error);
        })
        .finally(() => {
            // resetForm(ruleFormRef.value);
        });
};

// 倒计时
const startCountdown = () => {
    isCountingDown.value = true;
    buttonText.value = `${countdown.value}秒后重试`;
    timer = setInterval(() => {
        countdown.value--;
        buttonText.value = `${countdown.value}秒后重试`;

        if (countdown.value <= 0) {
            clearInterval(timer);
            timer = null;
            isCountingDown.value = false;
            countdown.value = 30;
            buttonText.value = '获取验证码';
        }
    }, 1000);
};

// 校验表单，错误信息展示
const showErrorMessage = () => {
    let email = formData.value.email;
    let checkCode = formData.value.code;

    // 表单校验未通过
    if (email == '') {
        errorMessage.value = '请输入邮箱';
        showMessage.value = true;
        return;
    } else if (!regEmail.test(email)) {
        errorMessage.value = '邮箱格式错误，请更换后重试';
        showMessage.value = true;
        return;
    } else if (checkCode == '') {
        errorMessage.value = '请输入邮箱验证码';
        showMessage.value = true;
        return;
    } else if (!regCheckCode.test(checkCode)) {
        errorMessage.value = '邮箱验证码格式错误';
        showMessage.value = true;
        return;
    }
    // 展示加载弹窗
    dialogConfig.loginType = 2;
};

// 清除错误信息提示
const clearErrorMessage = (type: number) => {
    if (type == 0 && (errorMessage.value == '请输入邮箱' || errorMessage.value == '邮箱格式错误，请更换后重试')) {
        errorMessage.value = '';
        showMessage.value = false;
    } else if (type == 1 && (errorMessage.value == '请输入邮箱验证码' || errorMessage.value == '邮箱验证码格式错误')) {
        errorMessage.value = '';
        showMessage.value = false;
    }
};

defineExpose({ showPanel });
</script>

<style lang="scss" scoped>
.form-body-email {
    margin: 0px auto;
    width: 420px;
    padding-top: 80px;
    padding-bottom: 18px;
    flex-direction: column;

    .email {
        width: 320px;
        margin: 0px auto;
    }

    .checkCode {
        width: 320px;
        margin: 0px auto;
        display: flex;

        button {
            background: #ff3a3a;
            border-radius: 20px;
            width: 119px;
            height: 36px;
            line-height: 36px;
            font-size: 14px;
            color: #fff;
            border: none;
            margin-left: 10px;
            cursor: pointer;
        }

        .counting-down {
            background: #ddd;
            color: #fff;
        }
    }

    .error-message {
        margin-left: 68px;
        font-size: 12px;
        margin-bottom: 6px;
        color: #f84a4a;
    }

    .submit {
        width: 320px;
        margin: 0px auto;

        button {
            width: 100%;
            background: #ff3a3a;
            border-radius: 20px;
            line-height: 36px;
            height: 36px;
            font-size: 14px;
            color: #fff;
            border: none;
            cursor: pointer;
            margin-top: 10px;
        }
    }
}

.scan-login {
    width: 330px;
    margin: 0px auto;
    margin-top: 25px;

    .scan {
        display: flex;
        width: 330px;
        height: 220px;

        .left {
            width: 125px;
            height: 220px;

            img {
                width: 100%;
            }
        }

        .right {
            flex: 1;
            height: 220px;
            margin-left: 25px;
            display: flex;
            flex-direction: column;
            align-items: center;

            .a {
                font-size: 18px;
                color: #404040;
            }

            .b {
                width: 128px;
                width: 128px;
                margin: 13px 0px;

                img {
                    width: 100%;
                }
            }

            .c {
                font-size: 12px;
                margin-top: 10px;
                color: rgba(0, 0, 0, 0.4);

                span {
                    color: #0c73c2;
                    margin: 0px 3px;
                    cursor: pointer;
                }
            }
        }
    }

    .others {
        display: block;
        width: 118px;
        height: 28px;
        margin: 20px auto 0;
        padding-right: 0;
        font-size: 12px;
        border: 1px solid #979797;
        border-radius: 15px;
        line-height: 28px;
        text-align: center;
        color: rgba(0, 0, 0, 0.8);
        cursor: pointer;
    }
}

.page-container {
    display: flex;
    justify-content: center;
    align-items: center;
}

.is-loading {
    animation: rotating 2s linear infinite;
}

@keyframes rotating {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

:deep(.el-input__wrapper) {
    border-radius: 25px;
}
</style>
